<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthRequest;
use App\Models\{User,
    UserInfo,
    UserInfoDetail,
    MessageSetting,
    PointsLog,
    YfUserInfo,
    UserPrivacy,
    UserResource,
    WebConfig};
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    public function loginByPassword(AuthRequest $request)
    {
        $user = User::getByMobile($request->user_mobile);

        if (md5($request->password) != $user->userInfo->password) {
            return $this->failed("用户名或密码错误");
        }

        return $this->login($user);
    }

    public function loginByCode(AuthRequest $request)
    {
        // 校验验证码
        $res = VerificationCodesController::verify($request->user_mobile, $request->sms_key, $request->sms_code);

        if ($res['response'] != 'success') {
            $response = $res['response'];
            $message = $res['message'];

            return $this->$response($message);
        }

        return $this->login(User::getByMobile($request->user_mobile));
    }

    public function loginBySocial(AuthRequest $request)
    {
        if (!$user = User::getByOpenid($request->openid)) {
            $user = new User();
            $user->bind_id = $request->type . '_' . $request->openid;
            $user->bind_type = User::$bind_type[$request->type];
            $user->user_id = 0;
            $user->bind_time = now()->toDateTimeString();
            $user->save();
        }

        return $this->login($user);
    }

    public function login(User $user)
    {
        if ($token = auth('api')->login($user)) {
            // 生成后的token前缀必须为'bearer '，否则无效
            return $this->success([
                'access_token' => 'bearer ' . $token,
                'expires_in'   => auth('api')->factory()->getTTL() * 60,
            ]);
        }
    }

    public function signUp(AuthRequest $request, User $user, UserInfo $userInfo)
    {
        DB::transaction(function () use ($request, $user, $userInfo) {
            $dateTime = now()->toDateTimeString();
            $timestamp = now()->getTimestamp();
            $ip = get_ip();

            $userInfo->user_name = $request->user_mobile;
            $userInfo->password = $request->password;
            $userInfo->action_time = $timestamp;
            $userInfo->action_ip = $ip;
            $userInfo->session_id = uniqid();
            $userInfo->save();

            $user->bind_id = 'mobile_' . $request->user_mobile;
            $user->bind_type = User::$bind_type['mobile'];
            $user->user_id = $userInfo->user_id;
            $user->bind_time = $dateTime;
            $user->save();

            UserInfoDetail::insert([
                'user_mobile_verify' => 1,
                'user_name' => $request->user_mobile,
                'user_mobile' => $request->user_mobile,
                'area_code' => '86',
                'user_reg_time' => $timestamp,
                'user_count_login' => '1',
                'user_lastlogin_time' => $timestamp,
                'user_lastlogin_ip' => $ip,
                'user_reg_ip' => $ip,
                'user_avatar' => ''
            ]);

            // 初始化用户信息
            YfUserInfo::insert([
                'user_id' => $userInfo->user_id,
                'user_name' => $request->user_mobile,
                'user_mobile' => $request->user_mobile,
                'area_code' => '86',
                'user_regtime' => $dateTime
            ]);

            // 接收规定的 5 个信息，发货通知、付款成功提醒、商品咨询回复提醒、退款退货提醒、平台客服回复提醒
            MessageSetting::insert([
                'user_id' => $userInfo->user_id,
                'message_template_all' => '6,7,1,8,26',
                'setting_time' => $dateTime
            ]);

            // 注册获取积分
            $points = WebConfig::value('points_reg');
            UserResource::insert([
                'user_id' => $userInfo->user_id,
                'user_points' => $points
            ]);

            UserPrivacy::insert(['user_id' => $userInfo->user_id]);

            // 积分赠送记录
            PointsLog::insert([
                'user_id' => $userInfo->user_id,
                'user_name' => $request->user_mobile,
                'class_id' => 1,
                'points_log_points' => $points,
                'points_log_time' => $dateTime,
                'points_log_desc' => '会员注册',
                'points_log_flag' => 'reg'
            ]);
        });

        return $this->login($user);
    }

    public function logout()
    {
        auth('api')->logout();

        return $this->success('退出成功');
    }

    public function refreshToken()
    {
        return $this->success([
            'access_token' => 'bearer ' . auth('api')->refresh(),
            'expires_in'   => auth('api')->factory()->getTTL() * 60
        ]);
    }
}
